package ai4games_tests.maths;

import game2dai.maths.Geometry2D;
import processing.core.PApplet;

public class LineLinesIntersection extends PApplet {

	final int IRAD = 5;
	
	float[] xyCordsOneLine = new float[] { 100,50, 120,80, 240,20, 350,50, 350,150, 300,100, 250,150, 350,200, 150,260, 120,170, 50,150, 50,100, 100,50 };
	boolean continuousLine = true;
	float x0,y0,x1,y1;
	float[] ipoint = null;
	int stride;
	
	public void setup(){
		size(400,300);
		smooth();
		cursor(CROSS);
		x1 = 10;
		y0 = 10;
		x0 = width - 20;
		y1 = height - 30;
		ellipseMode(RADIUS);
		continuousLine = true;
		if(continuousLine)
			stride = 2;
		else
			stride = 4;
		
		System.out.println(xyCordsOneLine.length);
	}

	public void mousePressed(){
		x0 = x1 = mouseX;
		y0 = y1 = mouseY;
	}
	
	public void mouseDragged(){
		x1 = mouseX;
		y1 = mouseY;		
	}
	
	public void draw(){
		background(128);
		
		if(x0 != x1 || y0 != y1)
			ipoint = makeFloatArray(Geometry2D.line_lines_p(x0,y0,x1,y1, makeDoubleArray(xyCordsOneLine), continuousLine));
		else
			ipoint = new float[0];
		
		strokeWeight(1.2f);
		stroke(0,255,0);
		for(int p = 0; p < xyCordsOneLine.length - stride; p += stride){
			line(xyCordsOneLine[p], xyCordsOneLine[p+1],xyCordsOneLine[p+2], xyCordsOneLine[p+3]);
		}
		stroke(255);
		line(x0,y0,x1,y1);
		
		fill(200,200,255);
		noStroke();
		for(int p = 0; p < ipoint.length; p += 2)
			ellipse(ipoint[p], ipoint[p+1], IRAD, IRAD);
		
		fill(255,255,0);
		text("Number of intersections = " + ipoint.length/2, 10, height - 4);
	}

	public float[] makeFloatArray(double[] da){
		float[] fa = new float[da.length];
		for(int i = 0; i < fa.length; i++)
			fa[i] = (float)da[i];
		return fa;
	}
	
	public double[] makeDoubleArray(float[] fa){
		double[] da = new double[fa.length];
		for(int i = 0; i < da.length; i++)
			da[i] = fa[i];
		return da;
	}
	
	
	
}
